package com.tingyuge.base.thread.wang.chapter6;

public class ThreadService {
    private Thread threadExecute;

    private boolean finished = false;

    public void  execute(Runnable runnable){
        threadExecute = new Thread(){
            @Override
            public void run() {
                Thread child = new Thread(runnable);
                child.setDaemon(true);
                child.start();

                try {
                    //等子线程结束
                    child.join();
                    finished =true;
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        };
        threadExecute.start();
    }

    public void shutdown(long mills){
        long currentTime = System.currentTimeMillis();
        while (!finished){
            if((System.currentTimeMillis() - currentTime)>=mills){
                System.out.println("任务已经超时");
                threadExecute.interrupt();
                break;
            }

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {

                e.printStackTrace();
                System.out.println("执行线程被打断");
                break;
            }
        }


    }

    public static void main(String[] args) {
        ThreadService threadService = new  ThreadService();

        threadService.execute(()->{
     /*       while (true){

            }*/
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long startTime = System.currentTimeMillis();
        threadService.shutdown(7000);
        long  endTime = System.currentTimeMillis();
        System.out.println("总耗时:" +(endTime-startTime));
    }
}
